const fs = require("fs");
const pdf = require("pdf-parse"); // 需要安装pdf-parse库
const mysql = require("mysql2/promise"); // 需要安装mysql2库

// 连接数据库
const db = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "chengfeng_inn",
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

// 读取PDF文件内容
const pdfPath = "./static/2023前端面试上岸手册（八股文）(3).pdf";
fs.readFile(pdfPath, (err, buffer) => {
  if (err) {
    console.error("Error reading PDF file:", err);
    return;
  }
  pdf(buffer).then((data) => {
    const text = data.text;
    console.log("🚀 ~ pdf ~ text:", text);
    fs.writeFile("./static/test.txt", text, (err) => {
      if (err) throw err;
      console.log("The file has been saved!");
    });
    const questionsAndAnswers = extractQuestionsAndAnswers(text);
    // console.log("🚀 ~ pdf ~ questionsAndAnswers:", questionsAndAnswers);
    // insertIntoDatabase(questionsAndAnswers);
  });
});

// 提取问题和答案的函数
function extractQuestionsAndAnswers(text) {
  const lines = text.split("\n");
  console.log("🚀 ~ extractQuestionsAndAnswers ~ lines:", lines);
  const regex = /^(\d+\.)(.*)/; // 根据文档格式调整正则表达式
  const pageRegex = /^\d+\s*$/; // 页码正则
  const emptyRegex = /^$/; // 空行正则
  const questionsAndAnswers = [];
  const obj = {
    question: "",
    answer: "",
  };

  for (let i = 0; i < lines.length; i++) {
    const match = lines[i].match(regex);
    const pageMatch = lines[i].match(pageRegex);
    const emptyMatch = lines[i].match(emptyRegex);
    if (emptyMatch) {
      continue;
    }
    if (pageMatch) {
      continue;
    }
    if (match) {
      // 题目
      if (obj.answer) {
        questionsAndAnswers.push(obj);
      }
      obj.question = match[2].trim();
      obj.answer = "";
    } else {
      // 答案
      if (obj.question) {
        obj.answer = obj.answer + lines[i].trim();
      }
    }
  }

  return questionsAndAnswers;
}

// 插入数据到数据库的函数
async function insertIntoDatabase(questionsAndAnswers) {
  const insertSQL =
    "INSERT INTO interview_questions (question, answer, category_id) VALUES (?, ?, 1)";

  for (const { question, answer } of questionsAndAnswers) {
    try {
      await db.query(insertSQL, [question, answer]);
      console.log(`Inserted: ${question}`);
    } catch (err) {
      console.error("Error inserting data:", err);
    }
  }
}
